package com.suedawn.bookmanagesystem.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.format.FormatterRegistry;
import org.springframework.core.convert.converter.Converter;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
//            .allowedOriginPatterns("*") // 或 allowedOrigins("http://localhost:5173")
            .allowedOriginPatterns("http://localhost:5173") // 或 allowedOrigins("http://localhost:5173")
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .allowedHeaders("*")
            .allowCredentials(true)
            .maxAge(3600);
    }
    
    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 处理String到Integer的转换，将"null"字符串转为null
        registry.addConverter(new Converter<String, Integer>() {
            @Override
            public Integer convert(String source) {
                if (source.isEmpty() || "null".equals(source)) {
                    return null;
                }
                return Integer.valueOf(source);
            }
        });
        
        // 处理String到Boolean的转换，将"null"字符串转为null
        registry.addConverter(new Converter<String, Boolean>() {
            @Override
            public Boolean convert(String source) {
                if (source.isEmpty() || "null".equals(source)) {
                    return null;
                }
                return Boolean.valueOf(source);
            }
        });
        
        // 处理String到BigDecimal的转换，将"null"字符串转为null
        registry.addConverter(new Converter<String, BigDecimal>() {
            @Override
            public BigDecimal convert(String source) {
                if (source.isEmpty() || "null".equals(source)) {
                    return null;
                }
                return new BigDecimal(source);
            }
        });
        
        // 处理String到Date的转换，将"null"字符串转为null
        registry.addConverter(new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                if (source.isEmpty() || "null".equals(source)) {
                    return null;
                }
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    return format.parse(source);
                } catch (Exception e) {
                    throw new IllegalArgumentException("Invalid date format. Use: yyyy-MM-dd");
                }
            }
        });
    }
}